package com.yonyou.brigade.third_parties.zteitc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.order_center.service.IBriOrderService;
import com.yonyou.brigade.third_parties.zteitc.constants.ZteitcConstants;
import com.yonyou.brigade.third_parties.zteitc.service.IZteitcOrderService;
import com.yonyou.brigade.third_parties.zteitc.service.IZteitcPublicService;
import com.yonyou.brigade.util.operateutil.DateUtils;
import com.yonyou.brigade.ybz.service.IConvertService;
import com.yonyou.ybzboot.starter.common.util.StringUtil;
import com.yonyou.ybzboot.starter.mongodb.dao.IMongoDao;
import com.yonyou.ybzboot.starter.mongodb.model.CriteriaMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * Created by Administrator on 2018/12/26.
 */
@Service
public class ZteitcOrderServiceImpl implements IZteitcOrderService {

    @Autowired
    @Qualifier("zteitcPublicServiceImpl")
    IZteitcPublicService zteitcPublicService;

    @Autowired
    @Qualifier("convertServiceImpl")
    private IConvertService convertService;

    @Value("${zteitc.tradeFlightType}")
    private  String tradeFlightType;

    @Value("${zteitc.tradeHotelType}")
    private  String tradeHotelType;

    @Value("${zteitc.tradeTrainType}")
    private  String tradeTrainType;

    @Value("${cnv.baigade.system.code}")
    private String systemCode;

    @Value("${cnv.register.userId}")
    private String cnvRegisterUserId;

    @Value("${cnv.register.tenant}")
    private String cnvRegisterTenant;

    @Value("${cnv.register.cookie}")
    private String cnvRegisterCookie;

    @Autowired
    @Qualifier("briOrderServiceImpl")
    private IBriOrderService briOrderService;

    @Autowired
    private IMongoDao mongoDao;

    private static final Logger logger = LoggerFactory.getLogger(ZteitcOrderServiceImpl.class);

    @Override
    public void getFlightOrderList(String tenant, String orgpk, int channelId, String begin, String end) {

        //从中兴拉取订单
        JSONObject jsonObject = zteitcPublicService.findOrdersByMethod(tenant,orgpk,begin,end, ZteitcConstants.METHOD_FIND_AIRPLANE);
        if (jsonObject == null) {
            return;
        }
        int code = jsonObject.getIntValue("code");
        if (200 != code) {
            logger.error("调用中兴接口失败！");
            return;
        }
        JSONArray itineraryArr = jsonObject.getJSONArray("data");
        if(itineraryArr != null && itineraryArr.size() > 0){
            for (int i = 0; i < itineraryArr.size(); i++) {
                JSONObject orderJson = itineraryArr.getJSONObject(i);
                dealWithMongo(orderJson.getString("orderNum"), ZteitcConstants.FLIGHT_MONGO_ORDER_TABLENAME, orderJson);
                saveFlight(orderJson, tenant, orgpk,channelId);
            }
        }

    }

    @Override
    public void getHotelOrderList(String tenant, String orgpk, int channelId, String begin, String end) {
        //从中兴拉取订单
        JSONObject jsonObject = zteitcPublicService.findOrdersByMethod(tenant,orgpk,begin,end, ZteitcConstants.METHOD_FIND_HOTEL);
        if (jsonObject == null) {
            return;
        }
        int code = jsonObject.getIntValue("code");
        if (200 != code) {
            logger.error("调用中兴接口失败！");
            return;
        }
        JSONArray itineraryArr = jsonObject.getJSONArray("data");
        if(itineraryArr != null && itineraryArr.size() > 0){
            for (int i = 0; i < itineraryArr.size(); i++) {
                JSONObject orderJson = itineraryArr.getJSONObject(i);
                dealWithMongo(orderJson.getString("orderNum"), ZteitcConstants.HOTEL_MONGO_ORDER_TABLENAME, orderJson);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    if (orderJson.get("checkInDate") != null && orderJson.get("arrivalLateTime") != null) {
                        String checkinDate = orderJson.get("checkInDate").toString();
                        String arrivalLateTime = orderJson.get("arrivalLateTime").toString();
                        String lastesDate = "";
                        //arrivalLateTime可能是    HH:mm 或者    次日HH:mm  或者 ""
                        if(arrivalLateTime.length() == 0){
                            arrivalLateTime = "23:59:59";
                            lastesDate = checkinDate + " " + arrivalLateTime;
                        }
                        else if (arrivalLateTime.length() > 5){
                            arrivalLateTime = arrivalLateTime.substring(2);
                            lastesDate = checkinDate + " " + arrivalLateTime.concat(":00");
                            lastesDate = DateUtils.plusDay(1,format.parse(lastesDate));
                        }
                        else
                        {
                            lastesDate = checkinDate + " " + arrivalLateTime.concat(":00");
                        }

                        Date date = format.parse(lastesDate);
                        orderJson.put("arrivalLateTime",date);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                    logger.error("日期转换失败！");
                    return;
                }
                saveHotel(orderJson, tenant, orgpk,channelId);
            }
        }
    }

    @Override
    public void getTrainOrderList(String tenant, String orgpk, int channelId, String begin, String end) {
        //从中兴拉取订单
        JSONObject jsonObject = zteitcPublicService.findOrdersByMethod(tenant,orgpk,begin,end, ZteitcConstants.METHOD_FIND_TRAIN);
        if (jsonObject == null) {
            return;
        }
        int code = jsonObject.getIntValue("code");
        if (200 != code) {
            logger.error("调用中兴接口失败！");
            return;
        }
        JSONArray itineraryArr = jsonObject.getJSONArray("data");
        if(itineraryArr != null && itineraryArr.size() > 0){
            for (int i = 0; i < itineraryArr.size(); i++) {
                JSONObject orderJson = itineraryArr.getJSONObject(i);
                dealWithMongo(orderJson.getString("orderNum"), ZteitcConstants.TRAIN_MONGO_ORDER_TABLENAME, orderJson);
                String orderStatus_String = orderJson.getString("orderStatus");
                Integer orderStatus_int = Integer.parseInt(orderStatus_String);
                orderJson.put("orderStatus",orderStatus_int);
                if (orderJson.getString("arriveDate") != null && StringUtil.isNotEmpty(orderJson.getString("arriveDate"))) {
                    String arriveDate = orderJson.getString("arriveDate").concat(":00");
                    orderJson.put("arriveDate",arriveDate);
                }
                if (orderJson.getString("startDate") != null && StringUtil.isNotEmpty(orderJson.getString("startDate"))) {
                    String startDate = orderJson.getString("startDate").concat(":00");
                    orderJson.put("startDate",startDate);
                }
                saveTrain(orderJson, tenant, orgpk,channelId);
            }
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void saveFlight (JSONObject orderJson, String tenant, String orgpk,int channelId) {
//        进行数据转换
        logger.info("zteitc before convert:"+orderJson.toJSONString());
        JSONObject res = convertService.convert(tradeFlightType,systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, orderJson);
//        将订单保存或更新
        logger.info("zteitc after convert:"+res);
        if (res.getBoolean("success")) {
            JSONArray results = res.getJSONArray("result");
            if (results != null && results.size() > 0) {
                for (int j = 0; j < results.size(); j++) {
                    JSONObject jsonObject = results.getJSONObject(j);
                    JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                    String orderNo = orderCenter.getString("orderNo");
                    String userMobile = orderCenter.getString("userId");
                    JSONArray flightInfo = orderCenter.getJSONArray("flightInfo");
                    if (flightInfo != null && flightInfo.size() > 0) {
                        for (int i = 0; i < flightInfo.size(); i++) {
                            JSONObject flightInfoJSONObject = flightInfo.getJSONObject(i);
                            if( flightInfoJSONObject.getString("departureDate") != null && !StringUtil.isEmpty( flightInfoJSONObject.getString("departureDate"))){
                                String departureDate = flightInfoJSONObject.getString("departureDate") + ":00";
                                flightInfoJSONObject.put("departureDate",departureDate);
                            }
                            if(flightInfoJSONObject.getString("arriveDate") != null && !StringUtil.isEmpty( flightInfoJSONObject.getString("arriveDate") )){
                                String  arriveDate =  flightInfoJSONObject.getString("arriveDate") + ":00";
                                flightInfoJSONObject.put("arriveDate",arriveDate);
                            }

                        }
                    }
                    if (orderCenter != null) {
                        try {
                            briOrderService.saveFlight(orderCenter, orderNo, tenant, userMobile, ChannelEnum.ZTEITC.getName(), channelId);
                        } catch (ParseException e) {
                            e.printStackTrace();
                            logger.error("保存中兴机票订单时，日期类型转换出现错误",e.getMessage());
                        }
                    }
                }
            }
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void saveHotel (JSONObject orderJson, String tenant, String orgpk,int channelId){
        //        进行数据转换
        JSONObject res = convertService.convert(tradeHotelType,systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, orderJson);
        //        将订单保存或更新
        if (res.getBoolean("success")) {
            JSONArray results = res.getJSONArray("result");
            if (results != null && results.size() > 0) {
                for (int j = 0; j < results.size(); j++) {
                    JSONObject jsonObject = results.getJSONObject(j);
                    JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                    String orderNo = orderCenter.getString("orderNo");
                    String userMobile = orderCenter.getString("userId");
                    if (orderCenter != null) {
                        try {
                            briOrderService.saveHotel(orderCenter, orderNo, tenant, userMobile, ChannelEnum.ZTEITC.getName(), channelId);
                        } catch (ParseException e) {
                            e.printStackTrace();
                            logger.error("保存中兴酒店订单时，日期类型转换出现错误",e.getMessage());
                        }
                    }
                }
            }
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void saveTrain (JSONObject orderJson, String tenant, String orgpk,int channelId){
        //        进行数据转换
        JSONObject res = convertService.convert(tradeTrainType,systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, orderJson);
        //        将订单保存或更新
        if (res.getBoolean("success")) {
            JSONArray results = res.getJSONArray("result");
            if (results != null && results.size() > 0) {
                for (int j = 0; j < results.size(); j++) {
                    JSONObject jsonObject = results.getJSONObject(j);
                    JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                    String orderNo = orderCenter.getString("orderNo");
                    String userMobile = orderCenter.getString("userId");
                    if (orderCenter != null) {
                        briOrderService.saveTrain(orderCenter, orderNo, tenant, userMobile, ChannelEnum.ZTEITC.getName(), channelId);
                    }
                }
            }
        }
    }

    private void dealWithMongo(String orderId, String mongoName, JSONObject orderJson) {
        CriteriaMap criteriaMap = new CriteriaMap();
        criteriaMap.put("orderNum",orderId);
        List<JSONObject> ordersources = mongoDao.findByMap(criteriaMap, JSONObject.class, mongoName);
        if(ordersources != null && ordersources.size() > 0) {
            mongoDao.deleteByMap(criteriaMap, mongoName);
            mongoDao.getMongoTemplate().save(orderJson, mongoName);
        }
        else {
            mongoDao.getMongoTemplate().insert(orderJson, mongoName);
        }
    }
}
